package com.ssm.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.blog.dao.PermissionDAO;
import com.ssm.blog.dao.RoleDAO;
import com.ssm.blog.pojo.Role;
import com.ssm.blog.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private PermissionDAO permissionDAO;
    @Autowired
    private RoleDAO roleDAO;


    @Override
    public PageInfo<Role> getRolePagerModel(Role criteria, Integer page, Integer rows) {
        PageHelper.startPage(page, rows, "id desc");
        List<Role> roleList = roleDAO.getRoleList(criteria);
        PageInfo<Role> pager = new PageInfo<>(roleList);
        return pager;
    }

    @Override
    public void addRole(Role role) {
        roleDAO.addRole(role);
    }

    @Override
    public void updateRole(Role role) {
        roleDAO.updateRole(role);
    }


    @Override
    public void deleteRole(Integer id) {
        roleDAO.deleteRole(id);//删除角色
        roleDAO.deleteUserRoleByRoleId(id);//删除用户角色
        permissionDAO.deleteRolePermissionByRoleId(id);//删除角色权限
    }

    @Override
    public void addRolePermission(Integer roleId, Integer[] menuIds) {
        permissionDAO.deleteRolePermissionByRoleId(roleId);
        Map<String, Integer> param = new HashMap<String, Integer>();
        param.put("roleId", roleId);
        for (Integer id : menuIds) {
            param.put("menuId", id);
            permissionDAO.addRolePermission(param);
        }
    }

    @Override
    public List<Integer> getRoleMenuIds(Integer roleId) {
        return permissionDAO.getRolePermissionByRoleId(roleId);
    }

    @Override
    public List<Role> getRoleList(Role criteria) {
        return roleDAO.getRoleList(criteria);
    }

    @Override
    public void addUserRole(Integer userId, Integer[] roleIds) {
        Map<String, Integer> param = new HashMap<>();
        param.put("userId", userId);
        roleDAO.deleteUserRoleByUserId(userId);//先删除用户原有的角色
        if (roleIds != null) {
            for (Integer roleId : roleIds) {
                param.put("roleId", roleId);
                roleDAO.addUserRole(param);
            }
        }
    }

    @Override
    public List<Integer> getUserRoleIds(Integer userId) {
        return roleDAO.getUserRoleIds(userId);
    }

}
